package com.hankol.community

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.text.TextUtils
import androidx.lifecycle.Observer
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.MessageBus
import com.baselibrary.bean.VideoReadBean
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.toast
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.ARouterUtils.parseParams
import com.baselibrary.utils.EventBusUtils
import com.baselibrary.utils.StatusBarUtil
import com.baselibrary.activity.BaseActivity
import com.hankol.community.adapter.VideoDetailsAdapter
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.databinding.ActivityVideoDetailsBinding
import com.hankol.community.viewmodel.VideoDetailsViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @description 新版视频详情
 * @author 关忆北、
 * @time 2022/4/10 1:45 下午
 */
@Route(path = ActivityRouter.ACTIVITY.READ_VIDEO_DETAIL)
class VideoDetailsActivity : BaseActivity() {
    companion object {
        const val TYPE_MAIN_PAGE_RECOMMEND = 0
        const val TYPE_MY_PUBLISH = 1
        const val TYPE_MY_FOLLOW = 2
        const val TYPE_TOPIC = 3
        const val TYPE_CIRCLE = 4
        const val TYPE_JIU_JIAO = 5
        const val TYPE_COLLECT = 6
        const val TYPE_TOPIC_HOT = 7

    }

    val communityHelp: CommunityHelp = ActivityRouter.getARouterInterface(ActivityRouter.COMMUNITY.COMMUNITY_HELP)
    private lateinit var mViewModel: VideoDetailsViewModel
    private lateinit var mDataBinding: ActivityVideoDetailsBinding
    private lateinit var mAdapter: VideoDetailsAdapter
    private var currentId = 0
    private var btype = 0
    private var browseNum = 0
    private var isOpenComment = false
    private var bid: String? = null
    var sourceName: String = ""//访问来源
    private var mToppingCommentId: Long = 0
    private var pageNum = "0"
    private var callback: IActivityResult? = null

    var isCollection = false
    private var mCurrentItem = 0
    var mList = mutableListOf<VideoReadBean.DataBeanX.DataBean>()
    override fun getLayoutId(): Int {
        StatusBarUtil.setTranslucentStatus(this)
        return R.layout.activity_video_details
    }

    override fun init() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//共享元素 解决白屏
            postponeEnterTransition();
        }
        mViewModel = getActivityViewModelProvider(this).get(VideoDetailsViewModel::class.java)
        mDataBinding = getDataBinding<ActivityVideoDetailsBinding>()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        getParams1()
        mAdapter = VideoDetailsAdapter(this)
        mDataBinding.vpVideoDetails.adapter = mAdapter
        mViewModel.reqVideoDetails(this, pageNum, currentId.toLong(), btype.toLong(), if (bid.checkNotNull()) bid!! else "")
        initObserve()
        SensorsDataManager.instance.onCreateTime()
        SensorsDataManager.instance.setFormPagePos("动态")
        mDataBinding.vpVideoDetails.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                mCurrentItem = position
                if (mCurrentItem == mList.size - 1) {
                    "加载中，请稍后".toast()
                    //获取推荐列表
                    mViewModel.reqVideoDetails(this@VideoDetailsActivity, pageNum, currentId.toLong(), btype.toLong(), if (bid.checkNotNull()) bid!! else "")
                }
            }
        })
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initObserve() {
        mViewModel.videoDetailsLD.observe(this, Observer {
            if (it != null) {
                pageNum = it.nextCursor
                val list: ArrayList<VideoReadBean.DataBeanX.DataBean> = it.data
                if (mCurrentItem == 0) {
                    val bean = VideoReadBean.DataBeanX.DataBean()
                    bean.id = currentId
                    bean.bid = bid
                    list.add(0, bean) //将当前的添加到里面去
                    mList.addAll(list)
                }
                if (mCurrentItem != 0) {
                    mList.addAll(list)
                }
                mAdapter.setDataList(browseNum, isOpenComment, mToppingCommentId, mList)
                mAdapter.notifyDataSetChanged()
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    supportStartPostponedEnterTransition()
                }
            }
        })
    }

      fun getParams1() {
        val paramsList = parseParams(intent.extras!!, "id", "isOpenComment", "JumpType", "bid", "commentId", "source", "browseNum")
        if (paramsList.isNotEmpty() && !TextUtils.isEmpty(paramsList[0])) {
            currentId = paramsList[0].toInt()
            isOpenComment = paramsList[1].contains("true")
            if (paramsList[2].checkNotNull()) {
                btype = paramsList[2].toInt()
            }
            if (paramsList[3].checkNotNull()) {
                bid = paramsList[3]
            }
            if (paramsList[4].checkNotNull()) {
                mToppingCommentId = paramsList[4].toLong()
            }
            if (paramsList[5].checkNotNull()) {
                sourceName = paramsList[5]
            }
            if (paramsList[6].checkNotNull()) {
                browseNum = paramsList[6].toInt()
            }
        }
    }

    override fun onDestroy() {
        if (!isCollection) EventBusUtils.sendNotify(MessageBus.msgId_dynamic_collection_false)
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_back_close) {
            onBackPressed()
        }
    }


    fun setCallback(callback: IActivityResult) {
        this.callback = callback
    }


    fun setCollectionData(isCollection: Boolean) {
        this.isCollection = isCollection
    }


    interface IActivityResult {
        fun onIActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        callback?.onIActivityResult(requestCode, resultCode, data)
    }

}